/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swingDemoEvent;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;

/**
 *
 * @author Administrator
 */

public class App13_9 extends JFrame
{
  int x,y;
  JButton bt=new JButton("移动我");
  JTextField tf=new JTextField(50);
  public App13_9(String s)
  {
    super(s);
    setLayout(null);
    setBounds(100,100,300,300);        //设置窗口的位置和大小
    bt.setBounds(30,30,80,20);          //设置按钮的位置和大小
    bt.addKeyListener(new MyKey());    //设置内部类对象为事件监听者并向按钮bt注册
    tf.setBounds(60,200,170,20);
    add(bt);                           //将按钮添加到窗口中
    add(tf);
    setVisible(true);
    setResizable(false);               //设置窗口不可改变大小
  }
  public static void main(String[] args)
  {
    App13_9 frm=new App13_9("键盘事件");
    frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  }
  class MyKey extends KeyAdapter
  {
    public void keyPressed(KeyEvent e)    //按下按键时的处理操作
    {
      JButton but=(JButton)e.getSource();       //获取事件源
      x=but.getLocation().x;                  //返回按钮左边缘的x坐标
      y=but.getLocation().y;                  //返回按钮上边缘的y坐标
      if(e.getKeyCode()==KeyEvent.VK_UP)   //上箭头键
      { 
        y=y-2;
        if(y<=0) y=0;
       }
      else if(e.getKeyCode()==KeyEvent.VK_DOWN)    //下箭头键
      {
        y=y+2;
        if(y>=240) y=240;
      }
      else if(e.getKeyCode()==KeyEvent.VK_LEFT)    //左箭头键
      {
        x=x-2;
        if(x<=0) x=0;
      }
      else if(e.getKeyCode()==KeyEvent.VK_RIGHT)   //右箭头键
      {
        x=x+2;
        if(x>=200) x=200;
      }
      but.setLocation(x,y);            //将按钮放置在左上角坐标为(x,y)的位置
    }
    public void keyReleased(KeyEvent e)  //放开按键时的处理操作
    {
      String str="按钮左上角现在位置是("+x+","+y+")";
      tf.setText(str);
    }
  }
}
